package com.own.component.sms.core.util;

import com.own.component.common.exception.BusinessException;
import com.own.component.sms.core.core.SmsSendSpringHook;
import com.own.component.sms.core.em.SmsSendMethodEnum;
import com.own.component.sms.core.model.SmsSendModel;
import com.own.component.sms.core.property.SmsProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * SmsUtil
 *
 * @author chenxueli
 * @date 2022-08-15 11:53:00
 */
@Component
public class SmsUtil {

    private static SmsUtil INSTANCE;

    @Resource
    private SmsSendSpringHook smsSendSpringHook;
    @Resource
    private SmsProperties smsProperties;

    /**
     * 发送短信信息
     *
     * @param type  类型
     * @param model 消息内容
     */
    public static void send(SmsSendMethodEnum type, SmsSendModel model) {
        var util = INSTANCE.smsSendSpringHook.get(type);
        if (util != null) {
            util.send(model);
            return;
        }
        send(model);
    }

    /**
     * 发送短信信息
     *
     * @param model 消息内容
     */
    public static void send(SmsSendModel model) {
        var defaultMethod = INSTANCE.smsProperties.getDefaultMethod();
        if (defaultMethod == null) {
            throw new BusinessException("短信发送方式未配置");
        }
        var util = INSTANCE.smsSendSpringHook.get(defaultMethod);
        if (util == null) {
            throw new BusinessException("短信发送方式未配置");
        }
        util.send(model);
    }

    @PostConstruct
    public void init() {
        INSTANCE = this;
    }

}
